﻿using BCL.Tool;
using DevicesView.Logic.User;
using System.Windows;
using DevicesView.Logic.App;
using System.Collections.Generic;
using System.Linq;
namespace WpfControlTool.Windows
{
    /// <summary>
    /// WindowLogin2.xaml 的交互逻辑
    /// </summary>
    public partial class WindowLogin2 : Window
    {
        private readonly List<UserConfig> users;
        public WindowLogin2()
        {
            InitializeComponent();
            users = UserConfig.GetLoginUserNames();
            if (users != null)
                TextBoxName.TextChanged += TextBoxName_TextChanged;
            if (AppResource.CurrentResource.LoginUser != null)
                TextBoxName.Text = AppResource.CurrentResource.LoginUser.LoginName;
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            UserLogic userLogic = new UserLogic();
            string msg = null;
            if (string.IsNullOrEmpty(TextBoxPass.Password))
                msg = "请填写密码".Language();
            if (string.IsNullOrEmpty(TextBoxName.Text))
                msg = "请填写用户名".Language();
            if (msg != null)
            {
                TextBoxMsg.Text = msg;
                return;
            }
            int error = userLogic.Login(new UserConfig { LoginName = TextBoxName.Text, Password = TextBoxPass.Password, Remember = (bool)checkbox1.IsChecked });
            if (error == 0)
                DialogResult = true;
            else
                TextBoxMsg.Text = "登录失败:".Language() + ErrorCodeLogic.GetStr((ErrorCode)error);
        }

        private void TextBoxPass_PasswordChanged(object sender, RoutedEventArgs e)
        {
            if (TextBoxPass.Password.Trim() == "")
                TextBlockpassTip.Text = "请输入密码".Language();
            else
                TextBlockpassTip.Text = "";
        }

        private void Grid_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            DragMove();
        }

        private void Border_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            DialogResult = false;
            Close();
        }

        private void TextBoxName_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            string name = TextBoxName.Text.Trim();
            UserConfig user = users.FirstOrDefault(o => o.LoginName == name);
            if (user == null)
            {
                checkbox1.IsChecked = false;
                TextBoxPass.Password = "";
                return;
            }

            if (!user.Remember)
                return;
            checkbox1.IsChecked = true;
            TextBoxPass.Password = user.Password;
        }
    }
}
